package com.tanhua.server.service;

import com.tanhua.autoconfig.templates.AipFaceTemplate;
import com.tanhua.autoconfig.templates.HuanXinTemplate;
import com.tanhua.autoconfig.templates.OssTemplate;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.User;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {
    //调用dubbo服务,消费者
    @DubboReference
    private UserApi userApi;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private AipFaceTemplate aipFaceTemplate;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private MqMessageService mqMessageService;

    //根据手机号码查询用户
    public User findByMobile(String mobile) {
        return userApi.findByMobile(mobile);
    }

    //根据手机和验证码校验用户
    public Map loginVerification(String mobile, String code) {
        //1.获取redis中的验证码
        String redisCode=redisTemplate.opsForValue().get("CODE:"+mobile);
        //2.比较用户输入的验证码和redis的验证码是否一直
        if (StringUtils.isEmpty(redisCode)||!redisCode.equals(code)){
            //3.不一致就抛出异常,见统一异常处理器
            throw new BusinessException(ErrorResult.loginError());
        }
        //4.一致,就删除redis中的验证码数据
        redisTemplate.delete("CODE:"+mobile);
        //5.根据手机号码查询用户
        User user = userApi.findByMobile(mobile);
        //6.如果不存在就需要注册用户
        Boolean isNew = false;
        //定义类型
        String type="0101";
        if(user == null) {
            isNew = true;
            user = new User();
            user.setPassword("123456");
            user.setMobile(mobile);
            Long userId = userApi.save(user);
            user.setId(userId);
            //如果user为null就代表是一个新用户，就要将信息存储到环信当中
            huanXinTemplate.createUser("hx"+user.getId(),"123456");
            //注册成功以后要给user对象中的字段进行赋值
            user.setHxUser("hx"+user.getId());
            user.setHxPassword("123456");
            //将user对象更新到数据库当中
            userApi.update(user);
            type="0102";
        }
        //注意:在这里向rabbitMq中发送消息
        //构建消息返回的对象
      /*  Map map=new HashMap();
        map.put("userId",user.getId().toString());
        map.put("logTime",new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        map.put("type",type);
        //定义消息
        String message= JSON.toJSONString(map);
        //登录成功发送日志消息
        rabbitTemplate.convertAndSend("tanhua.log.exchange","log.user",message);*/
      mqMessageService.sendLogMessage(user.getId(),type,"log.user",null);

        //7.生成jwt的token字符串
        Map tokenMao=new HashMap();
        tokenMao.put("id",user.getId());
        tokenMao.put("mobile",user.getMobile());
        String token = JwtUtils.getToken(tokenMao);

        //8.构建返回
        Map retMap=new HashMap();
        retMap.put("token",token);
        retMap.put("isNew",isNew);
        return retMap;
    }

    //保存用户资料
    public void saveUserInfo(UserInfo info) {
        //保存数据库,这里需要调用Api
        userInfoApi.save(info);
    }

    //设置头像
    public void head(Long id, MultipartFile headPhoto) throws IOException {
        //1.上传到阿里云oss
        String imgUrl = ossTemplate.upload(headPhoto.getInputStream(), headPhoto.getOriginalFilename());
        //2.判断头像中是否包含人脸
        Boolean detect = aipFaceTemplate.detect(imgUrl);
        if (!detect){
            //todo:不包含(这里需要删除阿里云的图片)

            //见异常处理器
            throw new BusinessException(ErrorResult.faceError());
        }
        //3.调用API,更新userInfo,只需要id和需要更新的字段对象即可
        UserInfo info = new UserInfo();
        info.setId(id);
        info.setAvatar(imgUrl);
        userInfoApi.update(info);
    }
}
